﻿using System;
using System.Collections.Generic;
using System.Linq;
using Framework.Extensions;

namespace Framework.Sql
{
    public class InsertSqlBuilder : SqlBuilderBase
    {
        protected readonly List<string> ColumnNames = new List<string>();
        protected readonly List<object> ColumnValues = new List<object>();

        public InsertSqlBuilder(string connectionString, string tableName) : base(connectionString, tableName) { }

        public void AddUpdateColumn(string columnName, object value)
        {
            ColumnNames.Add(columnName);
            ColumnValues.Add(value);
        }

        public virtual int ExecuteSql()
        {
            var sql = string.Format("insert into {0} ({1}) values ({2}); select scope_identity()",
                                    TableName,
                                    ColumnNames.Select(c => "[" + c + "]").SeparateBy(", "),
                                    ColumnNames.Select(s => "@" + s).SeparateBy(", "));

            return ColumnNames
                .Select((s, i) => new {Name = s, Index = i})
                .Aggregate(new SqlExecutor(ConnectionString).WithCommand(sql),
                           (adder, a) => adder.AddParameter(a.Name, ColumnValues[a.Index] ?? DBNull.Value))
                .Exec();
        }
    }
}